package com.zhifou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhifou.common.Result;
import com.zhifou.entity.User;
import com.zhifou.mapper.UserMapper;
import com.zhifou.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhifou.shiro.JwtToken;
import com.zhifou.util.BcryptUtil;
import com.zhifou.util.JwtUtil;
import com.zhifou.util.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 知否技术
 * @since 2022-03-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result login(String username, String password) {

        // 先从数据库查询
        User user = this.getOne(new QueryWrapper<User>().eq("username", username));
        if (null == user) {
            Result.fail("用户不存在");
        }
        if (!BcryptUtil.match(password, user.getPassword())) {
            return Result.fail("密码错误");
        }
        String jwtToken = jwtUtil.createJwtToken(user.getId().toString(), 10 * 10);
        redisUtil.set("token_" + jwtToken, user, 60 * 10, TimeUnit.SECONDS);
        return Result.success(jwtToken);
    }
}
